import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import { Novel } from './novel.entity';
import { Chapter } from './chapter.entity';

@Injectable()
export class NovelService {
  constructor(
    @InjectRepository(Novel)
    private novelRepository: Repository<Novel>,
    @InjectRepository(Chapter)
    private chapterRepository: Repository<Chapter>,
  ) {}

  async findAll(search?: string, page = 1, limit = 10): Promise<{ novels: Novel[]; total: number }> {
    const where = search ? { title: Like(`%${search}%`) } : {};

    const [novels, total] = await this.novelRepository.findAndCount({
      where,
      relations: ['chapters'],
      order: { createdAt: 'DESC' },
      take: limit,
      skip: (page - 1) * limit,
    });

    return { novels, total };
  }

  async findOne(id: number): Promise<Novel> {
    const novel = await this.novelRepository.findOne({
      where: { id },
      relations: ['chapters'],
    });

    if (!novel) {
      throw new NotFoundException('小说不存在');
    }

    return novel;
  }

  async getChapters(novelId: number, page = 1, limit = 20): Promise<{ chapters: Chapter[]; total: number }> {
    const [chapters, total] = await this.chapterRepository.findAndCount({
      where: { novelId },
      order: { chapterIndex: 'ASC' },
      take: limit,
      skip: (page - 1) * limit,
    });

    return { chapters, total };
  }

  async getChapter(novelId: number, chapterIndex: number): Promise<Chapter> {
    const chapter = await this.chapterRepository.findOne({
      where: { novelId, chapterIndex },
    });

    if (!chapter) {
      throw new NotFoundException('章节不存在');
    }

    return chapter;
  }

  async updateShareCount(novelId: number): Promise<void> {
    await this.novelRepository.increment({ id: novelId }, 'shareCount', 1);
  }

  async getPopularNovels(limit = 10): Promise<Novel[]> {
    return this.novelRepository.find({
      order: { shareCount: 'DESC' },
      take: limit,
    });
  }

  async getCategories(): Promise<{ categories: string[] }> {
    const result = await this.novelRepository
      .createQueryBuilder('novel')
      .select('DISTINCT novel.category', 'category')
      .where('novel.category IS NOT NULL')
      .andWhere('novel.category != :empty', { empty: '' })
      .getRawMany();

    const categories = result.map(item => item.category).filter(Boolean);
    return { categories };
  }

  async getNovelsByCategory(
    categoryName: string,
    page = 1,
    limit = 10,
  ): Promise<{ novels: Novel[]; total: number }> {
    const [novels, total] = await this.novelRepository.findAndCount({
      where: { category: categoryName },
      relations: ['chapters'],
      order: { createdAt: 'DESC' },
      take: limit,
      skip: (page - 1) * limit,
    });

    return { novels, total };
  }

  // 创建测试数据
  async createTestData(): Promise<void> {
    const testNovels = [
      {
        title: '人生模拟：让女剑仙抱憾终身',
        author: '佚名',
        source: 'fanqie',
        sourceUrl: 'https://fanqienovel.com/page/7345263292995384111',
        category: '都市修仙',
        description: '一个现代青年获得人生模拟器，在修仙世界搅动风云的故事',
        wordCount: '120万字',
        status: 0,
        chapterCount: 150,
        shareCount: 25,
      },
      {
        title: '霸道总裁爱上我',
        author: '甜心',
        source: 'fanqie',
        sourceUrl: 'https://fanqienovel.com/page/7345263292995384222',
        category: '现代言情',
        description: '一个普通女孩与霸道总裁的爱情故事',
        wordCount: '80万字',
        status: 1,
        chapterCount: 200,
        shareCount: 15,
      },
      {
        title: '星际征途',
        author: '科幻作家',
        source: 'fanqie',
        sourceUrl: 'https://fanqienovel.com/page/7345263292995384333',
        category: '科幻末世',
        description: '人类在星际时代的生存与扩张',
        wordCount: '200万字',
        status: 0,
        chapterCount: 300,
        shareCount: 8,
      },
      {
        title: '重生之商业帝国',
        author: '商战高手',
        source: 'fanqie',
        sourceUrl: 'https://fanqienovel.com/page/7345263292995384444',
        category: '都市重生',
        description: '重生过去，打造商业帝国',
        wordCount: '150万字',
        status: 1,
        chapterCount: 180,
        shareCount: 12,
      },
      {
        title: '仙界无敌',
        author: '仙侠作者',
        source: 'fanqie',
        sourceUrl: 'https://fanqienovel.com/page/7345263292995384555',
        category: '古典仙侠',
        description: '凡人逆天改命，成就仙界无敌传说',
        wordCount: '300万字',
        status: 0,
        chapterCount: 500,
        shareCount: 30,
      },
      {
        title: '校园青春',
        author: '青春文学',
        source: 'fanqie',
        sourceUrl: 'https://fanqienovel.com/page/7345263292995384666',
        category: '青春校园',
        description: '青春校园的美好时光',
        wordCount: '50万字',
        status: 1,
        chapterCount: 100,
        shareCount: 6,
      },
      {
        title: '魔法学徒',
        author: '奇幻大师',
        source: 'fanqie',
        sourceUrl: 'https://fanqienovel.com/page/7345263292995384777',
        category: '西幻奇幻',
        description: '一个魔法学徒的成长之路',
        wordCount: '180万字',
        status: 0,
        chapterCount: 250,
        shareCount: 10,
      },
      {
        title: '网游之王者归来',
        author: '网游作家',
        source: 'fanqie',
        sourceUrl: 'https://fanqienovel.com/page/7345263292995384888',
        category: '虚拟网游',
        description: '在虚拟世界中成为王者的故事',
        wordCount: '220万字',
        status: 0,
        chapterCount: 400,
        shareCount: 20,
      },
    ];

    for (const novelData of testNovels) {
      const existingNovel = await this.novelRepository.findOne({
        where: { sourceUrl: novelData.sourceUrl },
      });

      if (!existingNovel) {
        const novel = this.novelRepository.create(novelData);
        await this.novelRepository.save(novel);
        console.log(`✅ 创建测试小说: ${novel.title}`);
      } else {
        console.log(`⏭️  小说已存在: ${existingNovel.title}`);
      }
    }
  }
}